/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.gis.service.impl;

import me.zhengjie.domain.AreaConf;
import me.zhengjie.modules.gis.domainSmart.MesAreaData;
import me.zhengjie.modules.gis.domainTrans.TransAreaData;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.gis.repository.AreaConfRepository;
import me.zhengjie.modules.gis.service.AreaConfService;
import me.zhengjie.modules.gis.service.dto.AreaConfDto;
import me.zhengjie.modules.gis.service.dto.AreaConfQueryCriteria;
import me.zhengjie.modules.gis.service.mapstruct.AreaConfMapper;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author ZhuangBing Yan
* @date 2022-09-07
**/
@Service
@RequiredArgsConstructor
public class AreaConfServiceImpl implements AreaConfService {

    private final AreaConfRepository areaConfRepository;
    private final AreaConfMapper areaConfMapper;
    @PersistenceContext(unitName="entityManagerFactoryLvsmart")
    private EntityManager entityManagerMes;
    @PersistenceContext(unitName="entityManagerFactoryEladmin")
    private EntityManager entityManagerAdmin;

    @PersistenceContext(unitName="entityManagerFactoryTrans")
    private EntityManager entityManagerTrans;

    @Override
    public Map<String,Object> queryAll(AreaConfQueryCriteria criteria, Pageable pageable){
        Page<AreaConf> page = areaConfRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(areaConfMapper::toDto));
    }

    @Override
    public List<AreaConfDto> queryAll(AreaConfQueryCriteria criteria){
        return areaConfMapper.toDto(areaConfRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public AreaConfDto findById(Long id) {
        AreaConf areaConf = areaConfRepository.findById(id).orElseGet(AreaConf::new);
        ValidationUtil.isNull(areaConf.getId(),"AreaConf","id",id);
        return areaConfMapper.toDto(areaConf);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AreaConfDto create(AreaConf resources) {
        return areaConfMapper.toDto(areaConfRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AreaConf resources) {
        AreaConf areaConf = areaConfRepository.findById(resources.getId()).orElseGet(AreaConf::new);
        ValidationUtil.isNull( areaConf.getId(),"AreaConf","id",resources.getId());
        areaConf.copy(resources);
        areaConfRepository.save(areaConf);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            areaConfRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AreaConfDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AreaConfDto areaConf : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("项目地名字", areaConf.getGisAreaName());
            map.put("项目地坐标", areaConf.getPosition());
            map.put("1代表苏再生2代表转运中心3代表其他", areaConf.getType());
            map.put("火星坐标系(高德地图默认火星坐标系)", areaConf.getPositionGcj02());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<AreaConfDto> listbyIds(Long[] ids) {
        List<AreaConf> dtos = areaConfRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            Predicate like = root.get("id").in(ids);
            return criteriaQuery.where(like).getRestriction();
        });
        return areaConfMapper.toDto(dtos);
    }


    //批量插入
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertBatch(List<AreaConf> list) {
        for (AreaConf areaConf : list) {
            entityManagerAdmin.persist(areaConf);//insert插入操作
        }
        entityManagerAdmin.flush();
        entityManagerAdmin.clear();
    }

    //批量更新
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatch(List<AreaConf> list) {
        for (AreaConf areaConf : list) {
            entityManagerAdmin.merge(areaConf);//update操作
        }
        entityManagerAdmin.flush();
        entityManagerAdmin.clear();
    }

    //获取MES系统的地磅地点信息
    @Override
    @SuppressWarnings("unchecked")
    public List<MesAreaData> getMesAreaDataList(Integer type) {

        String sql1="select distinct source_unit as sourceUnit, area, transport_unit_inner_code as transportUnitInnerCode from vortex_szzszy " +
                "where transport_unit_inner_code = 1 and (data_operate = 0 or data_operate = 1)" ;
        String sql2="select distinct handle_unit as handleUnit, transport_unit_inner_code as transportUnitInnerCode from vortex_szzszy " +
                "where transport_unit_inner_code = 0 and (data_operate = 0 or data_operate = 1)";

        Query contentQuery = entityManagerMes.createNativeQuery(type == 0 ? sql2 : sql1);
        contentQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(MesAreaData.class));
        return contentQuery.getResultList();
    }


    //获取事业部地磅系统的地磅地点信息
    @Override
    @SuppressWarnings("unchecked")
    public List<TransAreaData> getTransAreaDataList(Integer type) {

        String sql1="SELECT distinct unit_name as sourceUnit, '1' as transportUnitInnerCode FROM dispatch_manager_inout " +
                "where list_type = '工程单' or list_type = '采购单' " ;
        String sql2="SELECT distinct unit_name as sourceUnit, Project_Name as projectName, '0' as transportUnitInnerCode FROM dispatch_manager_inout " +
                "inner join table_warehouse_weight_list on dispatch_manager_inout.uniquekey = table_warehouse_weight_list.UniqueKey " +
                "where dispatch_manager_inout.list_type = '销售单' " ;

        Query contentQuery = entityManagerTrans.createNativeQuery(type == 0 ? sql2 : sql1);
        contentQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(TransAreaData.class));
        return contentQuery.getResultList();
    }
}